﻿var grid = null;
var menu = null;
var startDate = null;
var endDate = null;
var copyValueList = [];
var checkedCategory = null;
var checkedCell = null;
var checkedCellTdList = [];
var isAddContinue = false;
var clicks = 0;
var index1 = 0;
var index2 = 0;
var win = null;
var templateComboBox = null;
var editRowStatus = 0;

$(function () {
    menu = $.ligerMenu({
        top: 100, left: 100, width: 100,
        items: [
        { id: '', text: '复制', click: contextMenuEvent },
        { id: '', text: '粘贴', click: contextMenuEvent },
        { id: '', text: '删除', click: contextMenuEvent },
        ]
    });

    $("#hdnCycleId").val("");

    var flag1 = false;
    $("#scheduleCycle").ligerComboBox({
        width: 50,
        cancelable: false,
        url: "/Scheduling/Scheduling/GetScheduleCycleList?ram" + Math.random(),
        valueField: "Id",
        textField: "TypeName",
        onSelected: function (value) {
            var cycleId = $("#hdnCycleId").val();
            if (cycleId != value) {
                var now = new Date();
                now = new Date(now.getTime() - (now.getDay() - 1) * 24 * 60 * 60 * 1000);
                startDate = now.Format("yyyy-MM-dd");
                now = new Date(startDate.replace(/-/g, '/'));
                if (value == $("#scheduleCycle").ligerComboBox().findValueByText("周")) {
                    now.setDate(now.getDate() + 6);
                }
                if (value == $("#scheduleCycle").ligerComboBox().findValueByText("双周")) {
                    now.setDate(now.getDate() + 13);
                }
                $("#hdnCycleId").val(value);

                endDate = now.Format("yyyy-MM-dd");
            }
            if (flag1) search();
            flag1 = true;
        },
        onSuccess: function (data) {
            $("#scheduleCycle").ligerComboBox().setValue($("#scheduleCycle").ligerComboBox().findValueByText("周"));
        }
    });

    var flag2 = false;
    $("#departmentCode").ligerComboBox({
        width: 100,
        cancelable: false,
        url: "/Scheduling/Scheduling/GetDepartmentList?ram" + Math.random(),
        valueField: "value",
        textField: "text",
        valueFieldID: 'hdnDepartmentCode',
        onSuccess: function (data) {
            $("#departmentCode").ligerComboBox().setValue($("#hdnCurrDepCode").val());
            flag2 = true;
        },
        onSelected: function (value) {
            if (flag1 && flag2) {
                search();
                bindSchedulingTemplate();
            }
        }
    });

    $("#btnPrevCycle").click(function () {
        showSchedulingDate(0);
    });
    $("#btnNextCycle").click(function () {
        showSchedulingDate(1);
    });
    $("#btnShowTemplate").click(function () {
        showTemplate();
    });
    $("#btnSave").click(function () {
        save(0);
    });
    $("#btnSubmit").click(function () {
        save(1);
    });
    $("#btnTemplateSave").click(function () {
        save(2);
    });
    $("#btnDelete").click(function () {
        delScheduling();
    });
    $("#btnDeleteTemplate").click(function () {
        delTemplate();
    });
    $("#btnPrint").click(function () {
        print();
    });
    $("#btnPrintView").click(function () {
        printView();
    });
    $("#btnAddRow").click(function () {
        addRow();
    });
    $("#btnEditRow").click(function () {
        editRow();
    });
    $("#btnDelRow").click(function () {
        delRow();
    });
    $("#btnRowSave").click(function () {
        editRowSave();
    });

    var t1 = window.setInterval(function () {
        if (flag1 && flag2) {
            search();
            bindCategory();
            bindSchedulingTemplate();
            bindRemark();
            window.clearInterval(t1);
        }
    }, 200);
});

//屏蔽鼠标右键
document.oncontextmenu = function () {
    return false;
}

//右击事件
function contextMenuEvent(item, i) {
    if (i == 0) {
        $(".checkedRowCellCopy").removeClass("checkedRowCellCopy");
        copyValueList = [];
        for (var i = 0; i < checkedCellTdList.length; i++) {
            copyValueList.push(checkedCellTdList[i]);
            $(checkedCellTdList[i]).find("div").first().addClass("checkedRowCellCopy");
            $(checkedCellTdList[i]).find("div").first().removeClass("checkedRowCell");
        }
    }
    else if (i == 1) {
        if (copyValueList.length == 1) {
            for (var i = 0; i < checkedCellTdList.length; i++) {
                grid.updateCell($(checkedCellTdList[i])[0], $(copyValueList[0]).find("div").first().html());
            }
            $(".checkedRowCellCopy").removeClass("checkedRowCellCopy");
        }
        else {
            var flag = true;
            if (copyValueList.length != checkedCellTdList.length) {
                flag = false;
            }
            if (flag) {
                var copyRowList = [];//按顺序排列复制的单元格
                var rowIndexList = [];
                for (var i = 0; i < copyValueList.length; i++) {
                    var rowIndex = $(copyValueList[i]).attr("id").split("|")[2].replace("r", "");
                    if (rowIndexList.indexOf(rowIndex) == -1) {
                        rowIndexList.push(rowIndex);
                        var cellIndexList = [];
                        $("[id^='maingrid|2|r" + rowIndex + "|']").each(function () {
                            if (!$(this).find("div").first().hasClass("checkedRowCellCopy")) {
                                return true;
                            }
                            var cellIndex = $(this).attr("id").split("|")[3].replace("c", "");
                            if (cellIndexList.indexOf(cellIndex) == -1) {
                                cellIndexList.push(cellIndex);
                            }
                        });
                        copyRowList.push({ rowIndex: rowIndex, cellIndexList: cellIndexList });
                    }
                }
                copyRowList.sort(function (a, b) {
                    return a.rowIndex - b.rowIndex;
                });

                var pasteRowList = [];//按顺序排列粘贴的单元格
                rowIndexList = [];
                for (var i = 0; i < checkedCellTdList.length; i++) {
                    var rowIndex = $(checkedCellTdList[i]).attr("id").split("|")[2].replace("r", "");
                    if (rowIndexList.indexOf(rowIndex) == -1) {
                        rowIndexList.push(rowIndex);
                        var cellIndexList = [];
                        $("[id^='maingrid|2|r" + rowIndex + "|']").each(function () {
                            if (!$(this).find("div").first().hasClass("checkedRowCell")) {
                                return true;
                            }
                            var cellIndex = $(this).attr("id").split("|")[3].replace("c", "");
                            if (cellIndexList.indexOf(cellIndex) == -1) {
                                cellIndexList.push(cellIndex);
                            }
                        });
                        pasteRowList.push({ rowIndex: rowIndex, cellIndexList: cellIndexList });
                    }
                }
                pasteRowList.sort(function (a, b) {
                    return a.rowIndex - b.rowIndex;
                });

                var pasteRowIndex = 0;
                for (var i = 0; i < copyRowList.length; i++) {//校验单元格
                    if (i == 0) {
                        pasteRowIndex = parseInt(pasteRowList[0].rowIndex);
                    }
                    else {
                        pasteRowIndex += parseInt(copyRowList[i].rowIndex) - parseInt(copyRowList[i - 1].rowIndex);
                    }

                    var pasteCellIndex = 0;
                    for (var ii = 0; ii < copyRowList[i].cellIndexList.length; ii++) {
                        if (ii == 0) {
                            if (i == 0) {
                                pasteCellIndex = parseInt(pasteRowList[0].cellIndexList[0]);
                            }
                            else {
                                pasteCellIndex = parseInt(pasteRowList[i - 1].cellIndexList[0]) + (parseInt(copyRowList[i].cellIndexList[0]) - parseInt(copyRowList[i - 1].cellIndexList[0]));
                            }
                        }
                        else {
                            pasteCellIndex += parseInt(copyRowList[i].cellIndexList[ii]) - parseInt(copyRowList[i].cellIndexList[ii - 1]);
                        }


                        if (!$(document.getElementById("maingrid|2|r" + pasteRowIndex + "|c" + pasteCellIndex)).find("div").first().hasClass("checkedRowCell")) {
                            flag = false;
                            break;
                        }
                    }
                }
            }
            if (flag) {
                var pasteRowIndex = 0;
                for (var i = 0; i < copyRowList.length; i++) { //校验单元格
                    if (i == 0) {
                        pasteRowIndex = parseInt(pasteRowList[0].rowIndex);
                    }
                    else {
                        pasteRowIndex += parseInt(copyRowList[i].rowIndex) - parseInt(copyRowList[i - 1].rowIndex);
                    }

                    var pasteCellIndex = 0;
                    for (var ii = 0; ii < copyRowList[i].cellIndexList.length; ii++) {
                        if (ii == 0) {
                            if (i == 0) {
                                pasteCellIndex = parseInt(pasteRowList[0].cellIndexList[0]);
                            }
                            else {
                                pasteCellIndex = parseInt(pasteRowList[i - 1].cellIndexList[0]) + (parseInt(copyRowList[i].cellIndexList[0]) - parseInt(copyRowList[i - 1].cellIndexList[0]));
                            }
                        }
                        else {
                            pasteCellIndex += parseInt(copyRowList[i].cellIndexList[ii]) - parseInt(copyRowList[i].cellIndexList[ii - 1]);
                        }
                        grid.updateCell(document.getElementById("maingrid|2|r" + pasteRowIndex + "|c" + pasteCellIndex), $(document.getElementById("maingrid|2|r" + copyRowList[i].rowIndex + "|c" + copyRowList[i].cellIndexList[ii])).find("div").first().html());
                    }
                }
                $(".checkedRowCellCopy").removeClass("checkedRowCell").removeClass("checkedRowCellCopy");
            }
            else {
                $.ligerDialog.error("复制跟粘贴的单元格不匹配");
            }
        }
    }
    else {
        for (var i = 0; i < checkedCellTdList.length; i++) {
            grid.updateCell($(checkedCellTdList[i])[0], "");
        }
    }
}

//绑定模板
function bindSchedulingTemplate() {
    templateComboBox = $("#schedulingTemplate").ligerComboBox({
        width: 140,
        cancelable: false,
        url: "/Scheduling/Scheduling/GetSchedulingTemplateList?ram" + Math.random(),
        parms: { departmentCode: $("#hdnDepartmentCode").val() },
        valueField: "Id",
        textField: "Name",
        valueFieldID: 'hdnTemplateId',
        value: 0,
        onSelected: templateComboBox != null ? null : function (value) {
            search();
        }
    });
}

//切换排班日期
function showSchedulingDate(val) {
    var _startDate = new Date(startDate.replace(/-/g, '/'));
    _startDate.setDate(_startDate.getDate() - (val == 0 ? 7 : -7));
    startDate = _startDate.Format("yyyy-MM-dd");
    var _endDate = new Date(endDate.replace(/-/g, '/'));
    _endDate.setDate(_endDate.getDate() - (val == 0 ? 7 : -7));
    endDate = _endDate.Format("yyyy-MM-dd");

    templateComboBox.setValue(0);
}

//显示排班
function search(pageNumber) {
    var queryData = {
        startDate: startDate,
        endDate: endDate,
        departmentCode: $("#hdnDepartmentCode").val(),
        templateId: $("#hdnTemplateId").val()
    };
    var columns = getColumns();
    initTable(queryData, columns);
}

//加载列表
function initTable(queryData, columns) {
    if (grid == null) {
        grid = $("#maingrid").ligerGrid({
            height: '100%',
            url: '/Scheduling/Scheduling/Search?ram=' + Math.random(),
            parms: queryData,
            pageSize: 30,
            heightDiff: -35,
            usePager: false,
            rownumbers: false,
            enabledSort: false,
            rowDraggable: true,
            enabledEdit: true,
            columns: columns,
            rowDraggingRender: function () {
                clicks = 0;
                index1 = 0;
                index2 = 0;
                $(".rowchange").removeAttr('class');
                return "";
            },
            onBeforeEdit: function (row) {
                if (row.column.display == "岗责") {
                    var cell = document.getElementById("maingrid|1|" + row.record.__id + "|" + row.column.__id);
                    if (checkedCategory != null) {
                        var category = $("#" + checkedCategory);
                        var categoryId = category.attr("id").replace('category', '');

                        if (categoryId == 0) {
                            if ($(cell).children(":first").html() != "") {
                                grid.updateCell(cell, "");
                            }
                        } else {
                            var categoryCode = category.text();
                            var oldValue = "";
                            if (isAddContinue) {
                                oldValue = $(cell).children(":first").html();
                            }
                            grid.updateCell(cell, oldValue + " " + categoryCode);
                        }
                        return false;
                    }
                }
            },
            onBeforeSubmitEdit: function (editParm) {
                if (editParm.column.name == "SuperWorkHours") {
                    if (editParm.value == 0) {
                        editParm.value = "";
                    }
                }
            },
            onAfterShowData: grid != null ? null : function (data) {
                $('.l-grid2').unbind();

                $('.l-grid2').on('click', '.l-grid-row-cell-inner', function () {
                    if (!$(this).parent().hasClass("l-grid-row-cell-last")) {
                        checkedCell = this;
                        if (!window.event.ctrlKey) {
                            scheduling();
                            $(".checkedRowCell").each(function (i) {
                                if (this != checkedCell) {
                                    $(this).removeClass("checkedRowCell");
                                }
                            });
                        }

                        if ($(".checkedRowCellCopy").length > 0) {
                            $(".checkedRowCellCopy").each(function (i) {
                                if (this == checkedCell) {
                                    $(".checkedRowCellCopy").removeClass("checkedRowCell").removeClass("checkedRowCellCopy");
                                    copyValueList = [];
                                    return false;
                                }
                            });
                        }
                        $(checkedCell).addClass("checkedRowCell");
                    }
                });

                $('.l-grid2').on('mousedown', '.l-grid-row-cell-inner', function (e) {
                    if (!$(this).parent().hasClass("l-grid-row-cell-last")) {
                        if (e.which == 3) {
                            checkedCell = this;
                            if (!window.event.ctrlKey) {
                                $(".checkedRowCell").each(function (i) {
                                    if (this != checkedCell) {
                                        $(this).removeClass("checkedRowCell");
                                    }
                                });
                            }
                            if (!$(checkedCell).hasClass("checkedRowCell")) {
                                $(checkedCell).addClass("checkedRowCell");
                            }

                            checkedCellTdList = [];
                            $(".checkedRowCell").each(function (i) {
                                checkedCellTdList.push($(this).parent()[0]);
                            });

                            menu.show({ top: e.pageY, left: e.pageX });
                        }
                    }
                });

                var leaveData = getLeaveInfoList(); //休假信息

                var dataCount = 0;
                for (var i = 0; i < grid.columns.length; i++) {
                    if (grid.columns[i].name.toString().indexOf("D_") != -1) {
                        dataCount++;
                    }
                }

                var otherCount = grid.columns.length - dataCount - 1; //1是排班日期后的列数
                var index = otherCount * grid.getData().length;

                for (var i = 0; i < grid.getData().length; i++) {
                    var personnelId = grid.getData()[i].PersonnelId;
                    if (personnelId.indexOf('NEW') != -1) {
                        $($(".l-grid-row-cell-inner")[i * otherCount]).parent().css('color', '#D96D00');
                    }

                    for (var ii = otherCount; ii < grid.columns.length; ii++) {
                        var columnName = grid.columns[ii].name.toString();
                        if (columnName.indexOf("D_") != -1) {
                            var cell = $($(".l-grid-row-cell-inner")[index]);
                            var cellVal = grid.rows[i][grid.columns[ii].name.toString()];
                            var status = 100;
                            if (cellVal != null && cellVal != "") {
                                var cellValList = cellVal.split(',');
                                if (cellVal.indexOf("font") == -1) {
                                    cell.html('');
                                    var idList = cellValList[0].split('|');
                                    var codeList = cellValList[1].split('|');
                                    var colorList = cellValList[2].split('|');
                                    status = grid.getData()[i].Status;
                                    var newCellValue = "";
                                    for (var iii = 0; iii < idList.length; iii++) {
                                        newCellValue += "<font style=\"margin-left:4px; color:" + colorList[iii] + "\" color=\"" + colorList[iii] + "\" categoryId=\"" + idList[iii] + "\" status=\"" + status + "\">" + codeList[iii] + "</font>";  //color单独添加时因为在IE10以上,、Chrome、Firefox中则是以GRB格式显示【rgb(255,0,0)】
                                    }
                                    grid.updateCell(cell.parent()[0], newCellValue);
                                }
                                else {
                                    var font = $(cellVal.replace(/"/g, "'")).eq(0);
                                    status = font.attr("status");
                                }
                            }
                            else {
                                if (personnelId.indexOf('NEW') == -1) {
                                    for (var j = 0; j < leaveData.length; j++) {
                                        if (leaveData[j].UserId == personnelId) {
                                            var tCurrDate = new Date(columnName.replace("D_", "")).getTime();
                                            var tLeaveStartDate = new Date(leaveData[j].StartTime.split(" ")[0]).getTime();
                                            var tLeaveEndDate = new Date(leaveData[j].EndTime.split(" ")[0]).getTime();
                                            if (tCurrDate >= tLeaveStartDate && tCurrDate <= tLeaveEndDate) {
                                                var day = ((tCurrDate - tLeaveStartDate) / 1000 / (24 * 60 * 60)) + 1;
                                                grid.updateCell(cell.parent()[0], "<font style=\"margin-left:4px;\" status=\"-1\">" + leaveData[j].TypeName + "第" + day + "天</font>");
                                                break;
                                            }
                                        }
                                    }
                                }
                            }

                            var node = $($(".l-grid-row-cell-inner")[index]).parent();
                            if (status == null) {
                                status = "100";
                            }
                            switch (status.toString()) {
                                case "0":
                                    node.css('background-color', '#FAF6DC');
                                    break;
                                case "1":
                                    node.css('background-color', '#CCFFCC');
                                    break;
                                case "2":
                                    node.css('background-color', '#FFE1FF');
                                    break;
                                default:
                                    node.css('background-color', '#FFFFFF');
                            }
                        }
                        index++;
                    }
                }

                grid.gridbody.bind('scroll.grid', function () {
                    $("#divCategory").click();
                });
            }
        });
        GridNoData($("#maingrid"));
    }
    else {
        grid = $("#maingrid").ligerGrid({
            url: '/Scheduling/Scheduling/Search?ram=' + Math.random(),
            parms: queryData,
            columns: columns
        });
    }
}

//绑定班别
function bindCategory() {
    $.ajax({
        url: "/Scheduling/Scheduling/GetSchedulingCategoryList",
        data: { departmentCode: $("#hdnDepartmentCode").val() },
        contentType: 'application/json;charset=utf-8',
        cache: false,
        success: function (data) {
            var d = $.parseJSON(data);
            if (d.Result == 1) {
                $("#divCategory").append($("<label onclick='chooseCategory()' id='category0' class='category'>清空</label>"));
                var categorylist = d.Body;
                for (var i = 0; i < categorylist.length; i++) {
                    $("#divCategory").append($("<label onclick='chooseCategory()' id='category" + categorylist[i].Id + "' color='" + categorylist[i].Color + "' class='category'  title='" + categorylist[i].Code + "'>" + categorylist[i].Code + "</label>"));
                }
                if ($("#divCategory").height() > 30) {
                    $("#displayCategory").show();
                }
                else {
                    $("#displayCategory").hide();
                }
            }
            else if (d.Result == 0) {
                $.ligerDialog.error(d.Body);
            }
            else {
                $.ligerDialog.error("程序错误");
            }
        },
        error: function () {
            $.ligerDialog.error("程序错误");
        }
    });
}

//隐藏班别
function showCategory(val) {
    if (val == 0) {
        $("#divCategory").removeAttr("style");
        $("#divCategory").css({ "float": "left", "width": "85%", "margin-left": "-10px" });
        var category_h = $("#divCategory").height();
        var grid_h = $("#maingridgrid").height();
        var grid1_h = $("#maingridgrid .l-grid1").children().last().height();
        var grid1_last_h = $("#maingridgrid .l-grid1").children().last().height();
        var grid2_h = $("#maingridgrid .l-grid2").children().last().height()
        var grid2_last_h = $("#maingridgrid .l-grid2").children().last().height();
        $("#maingridgrid").css("height", (grid_h + 30 - category_h) + "px");
        $("#maingridgrid .l-grid1").css("height", (grid1_h + 30 - category_h) + "px");
        $("#maingridgrid .l-grid1").children().last().css("height", (grid1_last_h + 30 - category_h) + "px");
        $("#maingridgrid .l-grid2").css("height", (grid2_h + 30 + category_h) + "px");
        $("#maingridgrid .l-grid2").children().last().css("height", (grid2_last_h + 30 - category_h) + "px");
        $("#displayCategory").text("隐藏<<");
        $("#displayCategory").attr('href', 'javascript:showCategory(1)');
    } else {
        var category_h = $("#divCategory").height();
        var grid_h = $("#maingridgrid").height();
        var grid1_h = $("#maingridgrid .l-grid1").children().last().height();
        var grid1_last_h = $("#maingridgrid .l-grid1").children().last().height();
        var grid2_h = $("#maingridgrid .l-grid2").children().last().height()
        var grid2_last_h = $("#maingridgrid .l-grid2").children().last().height();
        $("#maingridgrid").css("height", (grid_h - 30 + category_h) + "px");
        $("#maingridgrid .l-grid1").css("height", (grid1_h - 30 + category_h) + "px");
        $("#maingridgrid .l-grid1").children().last().css("height", (grid1_last_h - 30 + category_h) + "px");
        $("#maingridgrid .l-grid2").css("height", (grid2_h - 30 + category_h) + "px");
        $("#maingridgrid .l-grid2").children().last().css("height", (grid2_last_h - 30 + category_h) + "px");
        $("#divCategory").removeAttr("style");
        $("#divCategory").css({ "float": "left", "width": "85%", "height": "30px", "overflow": "hidden", "margin-left": "-10px" });
        $("#displayCategory").text("显示>>");
        $("#displayCategory").attr('href', 'javascript:showCategory(0)');
    }
}

//一直追加 
function addContinueClick() {
    if (!isAddContinue) {
        $("#btnAdd").removeClass("checkedAdd");
        $("#btnAddContinue").addClass("checkedAdd");
        isAddContinue = true;

    }
    else {
        $("#btnAddContinue").removeClass("checkedAdd");
        isAddContinue = false;
    }
}

//选择班别
function chooseCategory() {
    var obj = event.srcElement ? event.srcElement : event.target;
    if (checkedCategory != null) {
        if (checkedCategory == obj.id) {
            $("#" + checkedCategory).removeClass("checkedCategory");
            checkedCategory = null;
        }
        else {
            $("#" + checkedCategory).removeClass("checkedCategory");
            $("#" + obj.id).addClass("checkedCategory");
            checkedCategory = obj.id;
        }
    }
    else {
        $("#" + obj.id).addClass("checkedCategory");
        checkedCategory = obj.id;
    }
}

//【排班】
function scheduling() {
    if (checkedCategory != null) {
        var category = $("#" + checkedCategory);
        var categoryId = category.attr("id").replace('category', '');

        if (categoryId == 0) {
            if ($(checkedCell).html() != "") {
                grid.updateCell($(checkedCell).parent()[0], "");
            }
        } else {
            var categoryCode = category.text();
            var categoryColor = category.attr("color");

            var oldValue = "";
            if (isAddContinue) {
                oldValue = $(checkedCell).html();
            }
            grid.updateCell($(checkedCell).parent()[0], oldValue + "<font style=\"color:" + categoryColor + ";margin-left:4px;\" color=\"" + categoryColor + "\" categoryId=\"" + categoryId + "\" status=\"100\">" + categoryCode + "</font>");
        }
    }
}

//排班备注
function bindRemark() {
    $.ajax({
        url: "/Scheduling/SchedulingRemark/GetSchedulingRemark",
        data: { departmentCode: $("#hdnDepartmentCode").val() },
        contentType: 'application/json;charset=utf-8',
        cache: false,
        success: function (data) {
            var d = $.parseJSON(data);
            if (d.Result == 1) {
                var remark = d.Body.Remarks;
                if (remark.length > 60) {
                    $('#lblSchedulingRemark').text(remark.substring(0, 60) + "...");
                } else {
                    $('#lblSchedulingRemark').text(remark);
                    $("#linkSchedulingRemark").hide();
                }
                $("#divRemarkInfo").html(remark);
            }
            else if (d.Result == 0) {
                $("#linkSchedulingRemark").hide();
                $.ligerDialog.error(d.Body);
            }
            else {
                $.ligerDialog.error("程序错误");
            }
        },
        error: function () {
            $.ligerDialog.error("程序错误");
        }
    });
}

//排班备注
function showSchedulingRemark() {
    if (win) {
        win.show();
        $(".l-dialog").hide();
    }

    win = $.ligerDialog.open({
        title: '排班备注',
        target: $("#divRemarkInfo"),
        width: 400, height: 350, modal: true
    });
}

//获取表头
function getColumns() {
    var columns =
        [
            { display: '姓名', name: 'PersonnelName', width: 70, frozen: true },
            { display: '岗责', name: 'Remark', width: 90, frozen: true, editor: { type: 'text' } }
        ];

    $.ajax({
        url: "/Scheduling/Scheduling/GetDateTitle",
        data: { startDate: startDate, endDate: endDate },
        async: false,
        contentType: 'application/json;charset=utf-8',
        success: function (data) {
            var d = $.parseJSON(data);
            if (d.Result == 1) {
                for (var i = 0; i < d.Body.length; i++) {
                    var item = d.Body[i];
                    columns.push({ display: item.Date, columns: [{ display: (item.DayOfWeek == "六" || item.DayOfWeek == "日") ? ("<span style='color:red;'>" + item.DayOfWeek + "</span>") : item.DayOfWeek, name: item.DateId, width: 90, align: 'center' }] });
                }
            }
            else if (d.Result == 0) {
                $.ligerDialog.error(d.Body);
            }
            else {
                $.ligerDialog.error("程序错误");
            }
        },
        error: function () {
            $.ligerDialog.error("程序错误");
        }
    });

    columns[0].render = function (rowdata, rowindex, value) {
        return '<span onclick="rowChange(' + rowindex + ')">' + rowdata.PersonnelName + '</span>';
    }

    columns.push({ display: '总积休(小时)', name: 'SuperWorkHours', width: 100, editor: { type: 'float' }, render: function (row) { if (row.SuperWorkHours == 0) { return ''; } else { return row.SuperWorkHours } } });

    return columns;
}

//点击换班
function rowChange(index) {
    if (grid.rows[index]["PersonnelId"].indexOf('NEW') == 0) {
        $.ligerDialog.error('新增行无法和其他行更换');
        return false;
    }
    var currentid = ("000" + (index + 1)).substr(-3);
    var currentNode = $(document.getElementById('maingrid|1|r1' + currentid + '|c101')).children().children();
    clicks = (clicks + 1) % 2;
    if (clicks == 1) {
        index1 = index;
        currentNode.attr('class', 'rowchange');
    } else {
        index2 = index;
    }
    if (clicks == 0) {
        var id1 = ("000" + (index1 + 1)).substr(-3);
        var id2 = ("000" + (index2 + 1)).substr(-3);
        var node1 = $(document.getElementById('maingrid|1|r1' + id1 + '|c101')).children().children();
        var node2 = $(document.getElementById('maingrid|1|r1' + id2 + '|c101')).children().children();
        if (index1 != index2) {
            var middleId = grid.rows[index1]["PersonnelId"];
            var middleName = grid.rows[index1]["PersonnelName"];
            grid.rows[index1]["PersonnelId"] = grid.rows[index2]["PersonnelId"];
            grid.rows[index1]["PersonnelName"] = grid.rows[index2]["PersonnelName"];
            grid.rows[index2]["PersonnelId"] = middleId;
            grid.rows[index2]["PersonnelName"] = middleName;
            node1.text(grid.rows[index1]["PersonnelName"]);
            node2.text(middleName);
        }
        index1 = 0;
        index2 = 0;
        node1.removeAttr('class');
        node2.removeAttr('class');
    }
}

//显示保存为模板
function showTemplate() {
    if (win) {
        win.show();
        $(".l-dialog").hide();
        $("#txtTemplateName").val("");
    }

    win = $.ligerDialog.open({
        title: '保存模板',
        target: $("#divTemplate"),
        width: 300, height: 150, modal: true
    });
}

//保存排班或模板
function save(val) {
    var dateList = [];
    var otherList = [];
    for (var i = 0; i < grid.getData().length; i++) {
        otherItem = {};
        for (var ii = 0; ii < grid.columns.length; ii++) {
            var columnName = grid.columns[ii].name;
            var cellData = grid.rows[i][columnName];
            var dateItem = {};

            if (columnName.indexOf("D_") == -1) {
                if (columnName == "PersonnelName") {
                    otherItem.PersonnelId = grid.rows[i]["PersonnelId"];
                    otherItem.PersonnelName = cellData;
                }
                if (columnName == "Remark") {
                    otherItem.Remark = cellData;
                }
                if (columnName == "SuperWorkHours") {
                    otherItem.SuperWorkHours = cellData;
                }
            }
            else {
                dateItem.PersonnelId = otherItem.PersonnelId;
                dateItem.PersonnelName = otherItem.PersonnelName;
                dateItem.Remark = otherItem.Remark;
                dateItem.Status = val;
                if (cellData != "" && cellData != undefined && $(cellData).attr("categoryId") != undefined) {
                    var categoryId = "";
                    var categoryCode = "";
                    var categoryColor = "";
                    $(cellData.replace(/"/g, "'")).each(function () {
                        categoryId += $(this).attr("categoryId") + "|";
                        categoryCode += $(this).text() + "|";
                        categoryColor += $(this).attr("color") + "|";
                    });
                    dateItem.CategoryId = categoryId.substring(0, categoryId.length - 1);
                    dateItem.CategoryCode = categoryCode.substring(0, categoryCode.length - 1);
                    dateItem.CategoryColor = categoryColor.substring(0, categoryColor.length - 1);
                }
                dateItem.Sort = i + 1;
                dateItem.SchedulingDate = columnName.replace("D_", "");
                dateItem.DayOfWeek = grid.columns[ii].display.indexOf("span") == -1 ? grid.columns[ii].display : $(grid.columns[ii].display).text();
                dateItem.WeekNumber = Math.floor(Math.abs(Date.parse(startDate) - Date.parse(dateItem.SchedulingDate)) / (24 * 3600 * 1000)) < 7 ? 1 : 2;
                dateList.push(dateItem);
            }
        }
        otherList.push(otherItem);
    }
    var departmentCode = $("#hdnDepartmentCode").val();
    var url;
    var data;
    if (val == 2) {
        var template = {};
        template.Name = $("#txtTemplateName").val();
        template.CycleId = $("#hdnCycleId").val();
        template.CycleName = $("#scheduleCycle").ligerComboBox().getText();
        if (IsEmpty(template.Name)) {
            $.ligerDialog.error("模板名称不能为空");
            $("#txtTemplateName").focus();
            return;
        }

        url = "/Scheduling/Scheduling/SaveTemplate";
        data = { template: template, templateInfo: dateList, departmentCode: departmentCode };
    }
    else {
        url = "/Scheduling/Scheduling/Save";
        data = { schedulingList: dateList, schedulingOvertimeList: otherList, departmentCode: departmentCode };
    }

    var manager = $.ligerDialog.waitting('正在保存中,请稍候...');

    $.ajax({
        url: url,
        data: JSON.stringify(data),
        type: 'post',
        contentType: 'application/json;charset=utf-8',
        success: function (data) {
            var d = $.parseJSON(data);
            if (d.Result == 1) {
                if (val == 2) {
                    win.hide();
                    bindSchedulingTemplate();
                    $.ligerDialog.success("保存成功");
                }
                else {
                    $.ligerDialog.success(val == 0 ? "保存成功" : "提交成功");
                    setTimeout(function () { search(); }, 1000);
                }
                manager.close();
            }
            else if (d.Result == 0) {
                manager.close();
                $.ligerDialog.error(d.Body);
            }
            else {
                manager.close();
                $.ligerDialog.error("程序错误");
            }
        },
        error: function () {
            manager.close();
            $.ligerDialog.error("程序错误");
        }
    });
}

//删除模板
function delTemplate() {
    if ($("#hdnTemplateId").val() == 0) {
        $.ligerDialog.error("请选择模板");
        return false;
    }
    $.ligerDialog.confirm('确定删除？', function (value) {
        if (value) {
            var url = "/Scheduling/Scheduling/DelTemplate";
            $.ajax({
                url: url,
                type: "POST",
                cache: false,
                data: { id: $("#hdnTemplateId").val() },
                success: function (data) {
                    var d = $.parseJSON(data);
                    if (d.Result == 1) {
                        bindSchedulingTemplate();
                        $.ligerDialog.success("删除成功");
                    }
                    else if (d.Result == 0) {
                        $.ligerDialog.error(d.Body);
                    }
                    else {
                        $.ligerDialog.error("程序错误");
                    }
                },
                error: function () {
                    $.ligerDialog.error("程序错误");
                }
            });
        }
    });
}

//删除排班
function delScheduling() {
    $.ligerDialog.confirm('确定删除？', function (value) {
        if (value) {
            var url = "/Scheduling/Scheduling/DelScheduling";
            $.ajax({
                url: url,
                type: "POST",
                cache: false,
                data: { startDate: startDate, endDate: endDate, departmentCode: $("#hdnDepartmentCode").val() },
                success: function (data) {
                    var d = $.parseJSON(data);
                    if (d.Result == 1) {
                        $.ligerDialog.success("删除成功");
                        setTimeout(function () { search(); }, 1000);
                    }
                    else if (d.Result == 0) {
                        $.ligerDialog.error(d.Body);
                    }
                    else {
                        $.ligerDialog.error("程序错误");
                    }
                },
                error: function () {
                    $.ligerDialog.error("程序错误");
                }
            });
        }
    });
}

Install_InsertReport();
var Installed = Install_Detect();
if (Installed) {
    CreateReport("Report");
    Report.LoadFromURL($("#hdnGrfUrl").val());
}

//打印预览
function printView() {
    location.href = "/Scheduling/Scheduling/PrintView?startDate=" + startDate + "&endDate=" + endDate + "&templateId=" + $("#hdnTemplateId").val() + "&departmentCode=" + $("#hdnDepartmentCode").val();
}

//打印排班
function print() {
    try {
        Report.LoadDataFromURL("/Scheduling/Scheduling/GetSchedulingPrint?startDate=" + startDate + "&endDate=" + endDate + "&templateId=" + $("#hdnTemplateId").val() + "&departmentCode=" + $("#hdnDepartmentCode").val());
        Report.Print(true);
    }
    catch (e) {
        $('html,body').animate({ scrollTop: $(document).height() }, 1000);
    }
}

//获取休假信息
function getLeaveInfoList() {
    var leaveData = [];
    $.ajax({
        url: "/Scheduling/Leave/GetLeaveInfoList",
        data: { startDate: startDate, endDate: endDate, departmentCode: $("#hdnDepartmentCode").val() },
        contentType: 'application/json;charset=utf-8',
        cache: false,
        async: false,
        success: function (data) {
            var d = $.parseJSON(data);
            if (d.Result == 1) {
                leaveData = d.Body;
            }
            else if (d.Result == 0) {
                $.ligerDialog.error(d.Body);
            }
            else {
                $.ligerDialog.error("程序错误");
            }
        },
        error: function () {
            $.ligerDialog.error("程序错误");
        }
    });
    return leaveData;
}

//新增行
function addRow() {
    editRowStatus = 0;

    if (win) {
        win.show();
        $(".l-dialog").hide();
        $("#txtPersonnelName").val("");
    }

    win = $.ligerDialog.open({
        title: '新增行',
        target: $("#divEditRow"),
        width: 300, height: 150, modal: true
    });
}

//编辑行
function editRow() {
    editRowStatus = 1;
    var row = grid.getSelectedRow();
    if (!row || row.PersonnelId.indexOf('NEW') == -1) {
        $.ligerDialog.error("请选择新增的行");
        return false;
    }

    editRowIndex = row.__index;

    if (win) {
        win.show();
        $(".l-dialog").hide();
        $("#txtPersonnelName").val(row.PersonnelName);
    }

    win = $.ligerDialog.open({
        title: '编辑行',
        target: $("#divEditRow"),
        width: 300, height: 150, modal: true
    });
}

//新增或编辑行保存
function editRowSave() {
    var personnelName = $("#txtPersonnelName").val();
    if (IsEmpty(personnelName)) {
        $.ligerDialog.error("名称不能为空");
        $("#txtPersonnelName").focus();
        return;
    }

    if (editRowStatus == 1) {
        var row = grid.getSelectedRow();
        row.PersonnelName = personnelName;
        grid.updateRow(row, row);
    }
    else {
        var nearRow = grid.rows[grid.rows.length - 1];
        grid.addRow({ PersonnelName: personnelName, PersonnelId: "NEW" + new Date().getTime() }, nearRow, false);
    }
    win.hide();
}

//删除行
function delRow() {
    var row = grid.getSelectedRow();
    if (!row || row.PersonnelId.indexOf('NEW') == -1) {
        $.ligerDialog.error("请选择新增的行");
        return false;
    }
    grid.deleteSelectedRow();
}
